package com.wiken.commentservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wiken.commentservice.entity.Like;
import com.wiken.commentservice.mapper.LikeMapper;
import com.wiken.commentservice.service.ILikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wiken.servicecommon.common.Code;
import com.wiken.servicecommon.common.TokenUtil;
import com.wiken.servicecommon.common.exception.DefaultException;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wiken
 * @since 2022-12-28
 */
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements ILikeService {

    public boolean hasSameUser(Like like, String token){
        Claims claims = TokenUtil.parseToken(token);

        if(claims == null) throw new DefaultException(Code.ERROR_AUTHORIZATION_EXPIRATION, "操作异常");

        String userId = claims.get("userId", String.class);

        if(userId == null) throw new DefaultException(Code.ERROR_AUTHORIZATION_NULL, "操作异常");

        if(!userId.equals(like.getUserId())) throw new DefaultException(Code.ERROR_AUTHORIZATION, "操作异常");

        return true;
    }
    @Override
    public boolean like(Like like, String token) {
        hasSameUser(like, token);

        //判断是否点过赞，如果点过赞就取消点赞，如果没有点过赞就点赞
        Map<String, String> map = new HashMap();
        map.put("comment_id", like.getCommentId());
        map.put("user_id", like.getUserId());

        Integer count = baseMapper.selectCount(new QueryWrapper<Like>().allEq(map));

        //如果count>0说明点过赞,此时没有必要插入
        if(count > 0) return true;

        int success = baseMapper.insert(like);
        return success > 0;
    }

    @Override
    public boolean cancleLike(Like like, String token) {
        hasSameUser(like, token);

        Map<String, Object> params = new HashMap<>();
        params.put("comment_id", like.getCommentId());
        params.put("user_id", like.getUserId());

        int success = baseMapper.deleteByMap(params);
        return success > 0;
    }

    @Override
    public Integer getLikeNumberByCommentId(String commentId) {
        Integer count = baseMapper.selectCount(new QueryWrapper<Like>().eq("comment_id", commentId));
        return count;
    }

    @Override
    public boolean hasLike(String commentId, String userId) {
        Map<String, Object> params = new HashMap<>();

        params.put("comment_id", commentId);
        params.put("user_id", userId);

        Integer count = baseMapper.selectCount(new QueryWrapper<Like>().allEq(params));

        return count > 0;
    }
}
